﻿using System;
using System.Collections.Generic;
using System.Linq;
using YogaStudio.Data;
using YogaStudio.Data.Domain;

namespace YogaStudio.Service.BLL
{
    public class OrderService : IOrderService
    {
        private readonly YogaStudioEntities _dbContext = new YogaStudioEntities();
        
        public void CreateOrder(User currentUser, List<ShoppingCart> shoppingCartItems, PaymentDetail paymentDetails, Shipping shippingDetails)
        {
            var orderItems = shoppingCartItems.Select(shoppingCartItem => 
                new OrderItem                                                         
                {                              
                    ProductId = shoppingCartItem.ProductId, 
                    Quantity = shoppingCartItem.Quantity, 
                    Price = shoppingCartItem.Quantity * shoppingCartItem.Product.Price,                         
                }).ToList();

            var order = new Order
                        {
                            UserId = currentUser.UserId,
                            OrderDate = DateTime.Now,
                            PaymentDetails = paymentDetails,
                            Shipping = shippingDetails,
                            OrderItems = orderItems
                        };

            _dbContext.Orders.Add(order);
            _dbContext.SaveChanges();
        }

        public IQueryable<Order> GetAllOrdersByUserId(int userId)
        {
            return _dbContext.Orders.Where(x => x.UserId == userId);
        }

        public IQueryable<OrderItem> GetAllOrderItems(int orderId, int userId)
        {
            return _dbContext.OrderItems.Where(x => x.OrderId == orderId && x.Order.UserId == userId);
        }
    }
}